package com.blb.demo2;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 聊天的服务器端
 */
public class ChatServer {

    public static final int PORT = 8888;
    public static final int THREADS = 2;

    public void start(){
        //创建自定义线程池
        int cpus = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = new ThreadPoolExecutor(
                cpus * THREADS,
                cpus * THREADS,0, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>());
        System.out.println("启动聊天服务");
        try (ServerSocket serverSocket = new ServerSocket(PORT)){
            while (true){
                //获得客户端连接
                Socket client = serverSocket.accept();
                //获得输入流和输出流，启动两个线程分别完成读和写
                executorService.execute(new ReadRunnable(new ObjectInputStream(client.getInputStream())));
                executorService.execute(new WriteRunnable(new ObjectOutputStream(client.getOutputStream())));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ChatServer().start();
    }
}
